package com.hyyt.shopjsp.store.info.controller;

import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.store.info.service.IShopShopInfoService;
import com.hyyt.shopjsp.util.common.EnumUtils;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.export.ExportExcel;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺交易汇总Controller
 * LC
 */
@Controller
@RequestMapping("/back/shopTransactionSummary")
public class ShopTransactionSummaryController extends BaseController {

    private Logger log = Logger.getLogger(ShopTransactionSummaryController.class);
    private String basePath = "/back/shop/transactionSummary/";

    @Resource
    private IShopShopInfoService shopShopInfoService;//店铺service

    /**
     * 进入店铺交易汇总(日期)页
     *
     * @return 返回到指定页面
     */
    @RequestMapping("gotoTransactionsByDatePage")
    public String gotoTransactionsByDatePage(){
        return basePath+"transactionsByDateList";
    }

    /**
     * 查询交易汇总信息（日期）列表
     * @params page
     * @params shopName         店铺名称
     * @params createTimeStart  交易开始时间
     * @params createTimeEnd    交易结束时间
     * @params ordersState      订单状态
     * @params shopInfoType     店铺状态
     */
    @RequestMapping(value="ListTransactionsByDate",method= RequestMethod.POST)
    @ResponseBody
    public void ListTransactionsByDate(String shopName,String createTimeStart,String createTimeEnd,String ordersState,String shopInfoType,Page page, HttpServletResponse response){
        Map<String, Object> params = new HashMap<>();
        if(Utils.objectIsNotEmpty(shopName)){
            params.put("shopName",shopName.trim());
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart",createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd",createTimeEnd);
        }
        if(Utils.objectIsNotEmpty(ordersState)){
            params.put("ordersState",ordersState);
        }
        if(Utils.objectIsNotEmpty(shopInfoType)){
            params.put("shopInfoType",shopInfoType);
        }
        params.put("type","true");
        int totalRecordCount =shopShopInfoService.countShopTransactionSummary(params);
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<Map<String ,Object>> shopTransactionSummaryList =shopShopInfoService.queryShopTransactionSummary(params, page.getPageRecordBeginIndex(), page.getPageSize());
        if(Utils.objectIsNotEmpty(shopTransactionSummaryList)){
            for(Map<String,Object> map: shopTransactionSummaryList){
                //结算佣金
                BigDecimal commissionProportion = new BigDecimal(0);
                if(Utils.objectIsNotEmpty(map.get("commission"))){
                    commissionProportion = new BigDecimal(String.valueOf(map.get("commission")));
                }
                BigDecimal transactionAmount= new BigDecimal(0);//交易金额 (己完成交易)
                if(Utils.objectIsNotEmpty(map.get("transactionAmount"))){
                    transactionAmount=new BigDecimal(String.valueOf(map.get("transactionAmount")));
                }
                BigDecimal commissionAmount=new BigDecimal(commissionProportion.multiply(transactionAmount).doubleValue()/100);
                BigDecimal payableAmount = transactionAmount.subtract(commissionAmount);
                map.put("commissionProportion",commissionProportion);
                map.put("commissionAmount",commissionAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
                map.put("payableAmount",payableAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
            }
        }
        params.clear();
        params.put("total", totalRecordCount);// total键 存放总记录数，必须的
        params.put("rows", shopTransactionSummaryList);// rows键 存放每页记录 list
        ResultMsg.create(params, response);  //把内容发送到页面
    }


    /**
     * 进入店铺交易汇总(状态)页
     *
     * @return 返回到指定页面
     */
    @RequestMapping("gotoTransactionsByStatePage")
    public String gotoTransactionsByStatePage(){
        return basePath+"transactionsByStateList";
    }

    /**
     * 查询交易汇总信息（状态）列表
     * @params page
     * @params shopName         店铺名称
     * @params createTimeStart  交易开始时间
     * @params createTimeEnd    交易结束时间
     * @params ordersState      订单状态
     * @params shopInfoType     店铺状态
     */
    @RequestMapping(value="ListTransactionsByState",method= RequestMethod.POST)
    @ResponseBody
    public void ListTransactionsByState(String shopName,String createTimeStart,String createTimeEnd,String ordersState,String shopInfoType,Page page, HttpServletResponse response){
        Map<String, Object> params = new HashMap<>();
        if(Utils.objectIsNotEmpty(shopName)){
            params.put("shopName",shopName.trim());
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart",createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd",createTimeEnd);
        }
        if(Utils.objectIsNotEmpty(ordersState)){
            params.put("ordersState",ordersState);
        }
        if(Utils.objectIsNotEmpty(shopInfoType)){
            params.put("shopInfoType",shopInfoType);
        }
        int totalRecordCount =shopShopInfoService.countShopTransactionSummary(params);
        page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
        List<Map<String ,Object>> shopTransactionSummaryList =shopShopInfoService.queryShopTransactionSummary(params, page.getPageRecordBeginIndex(), page.getPageSize());
        if(Utils.objectIsNotEmpty(shopTransactionSummaryList)){
            for(Map<String,Object> map: shopTransactionSummaryList){
                //结算佣金
                BigDecimal commissionProportion = new BigDecimal(0);
                if(Utils.objectIsNotEmpty(map.get("commission"))){
                    commissionProportion = new BigDecimal(String.valueOf(map.get("commission")));
                }
                BigDecimal transactionAmount= new BigDecimal(0);//交易金额 (己完成交易)
                if(Utils.objectIsNotEmpty(map.get("transactionAmount"))){
                    transactionAmount=new BigDecimal(String.valueOf(map.get("transactionAmount")));
                }
                BigDecimal commissionAmount=new BigDecimal(commissionProportion.multiply(transactionAmount).doubleValue()/100);
                BigDecimal payableAmount = transactionAmount.subtract(commissionAmount);
                map.put("commissionProportion",commissionProportion);
                map.put("commissionAmount",commissionAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
                map.put("payableAmount",payableAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
                if(Utils.objectIsNotEmpty(createTimeStart)){
                    map.put("beginTime",createTimeStart);
                }else {
                    map.put("beginTime","--");
                }
                if(Utils.objectIsNotEmpty(createTimeEnd)){
                    map.put("endTime",createTimeEnd);
                }else {
                    map.put("endTime","--");
                }
            }
        }
        params.clear();
        params.put("total", totalRecordCount);// total键 存放总记录数，必须的
        params.put("rows", shopTransactionSummaryList);// rows键 存放每页记录 list
        ResultMsg.create(params, response);  //把内容发送到页面
    }


    /**
     * 导出交易汇总信息（日期）excel
     * @params page
     * @params shopName         店铺名称
     * @params createTimeStart  交易开始时间
     * @params createTimeEnd    交易结束时间
     * @params ordersState      订单状态
     * @params shopInfoType     店铺状态
     * @params request
     * @params response
     */
    @RequestMapping("exportTransactionsByDateExcel")
    public void exportTransactionsByDateExcel(String shopName, String createTimeStart, String createTimeEnd, String ordersState, String shopInfoType, HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> params = new HashMap<>();
        if(Utils.objectIsNotEmpty(shopName)){
            params.put("shopName",shopName.trim());
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart",createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd",createTimeEnd);
        }
        if(Utils.objectIsNotEmpty(ordersState)){
            params.put("ordersState",ordersState);
        }
        if(Utils.objectIsNotEmpty(shopInfoType)){
            params.put("shopInfoType",shopInfoType);
        }
        params.put("type","true");
        List<Map<String ,Object>> shopTransactionSummaryList =shopShopInfoService.queryShopTransactionSummary(params);
        if(Utils.objectIsNotEmpty(shopTransactionSummaryList)){
            for(Map<String,Object> map: shopTransactionSummaryList){
                //结算佣金
                BigDecimal commissionProportion = new BigDecimal(0);
                if(Utils.objectIsNotEmpty(map.get("commission"))){
                    commissionProportion = new BigDecimal(String.valueOf(map.get("commission")));
                }
                BigDecimal transactionAmount= new BigDecimal(0);//交易金额 (己完成交易)
                if(Utils.objectIsNotEmpty(map.get("transactionAmount"))){
                    transactionAmount=new BigDecimal(String.valueOf(map.get("transactionAmount")));
                }
                BigDecimal commissionAmount=new BigDecimal(commissionProportion.multiply(transactionAmount).doubleValue()/100);
                BigDecimal payableAmount = transactionAmount.subtract(commissionAmount);
                map.put("commissionProportion",commissionProportion);
                map.put("commissionAmount",commissionAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
                map.put("payableAmount",payableAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
            }
        }

        SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
        List<Map<String,Object>> transactionSummary = new ArrayList<>();
        if(shopTransactionSummaryList!=null&&shopTransactionSummaryList.size()>0){
            for (Map<String,Object> shopTransactionSummary : shopTransactionSummaryList) {
                Map<String,Object> map = new HashMap<>();
                map.put("companyName",shopTransactionSummary.get("companyName"));
                map.put("shopName", shopTransactionSummary.get("shopName"));
                map.put("transactionAmount", shopTransactionSummary.get("transactionAmount"));
                map.put("commissionProportion", shopTransactionSummary.get("commissionProportion"));
                map.put("commissionAmount", shopTransactionSummary.get("commissionAmount"));
                map.put("payableAmount", shopTransactionSummary.get("payableAmount"));
                map.put("createTime", shopTransactionSummary.get("createTime"));
                transactionSummary.add(map);
            }
        }

        String fileName ="交易汇总信息（日期）";
        String columnNames[] = {"公司名称","店铺名称","交易金额 (元)","佣金百分比(%)","佣金(元)","平台给店铺结算的应付金额(元)","统计日期"};
        String keys[] = {"companyName","shopName","transactionAmount","commissionProportion","commissionAmount","payableAmount","createTime"};
        try {
            ExportExcel.download(fileName,transactionSummary,columnNames,keys,request,response);
        } catch (IOException e) {
            logger.error("导出Excel失败！");
        }

    }


    /**
     * 导出交易汇总信息（状态）excel
     * @params page
     * @params shopName         店铺名称
     * @params createTimeStart  交易开始时间
     * @params createTimeEnd    交易结束时间
     * @params ordersState      订单状态
     * @params shopInfoType     店铺状态
     * @params request
     * @params response
     */
    @RequestMapping("exportTransactionsByStateExcel")
    public void exportTransactionsByStateExcel(String shopName,String createTimeStart,String createTimeEnd,String ordersState,String shopInfoType,HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> params = new HashMap<>();
        if(Utils.objectIsNotEmpty(shopName)){
            params.put("shopName",shopName.trim());
        }
        if(Utils.objectIsNotEmpty(createTimeStart)){
            params.put("createTimeStart",createTimeStart);
        }
        if(Utils.objectIsNotEmpty(createTimeEnd)){
            params.put("createTimeEnd",createTimeEnd);
        }
        if(Utils.objectIsNotEmpty(ordersState)){
            params.put("ordersState",ordersState);
        }
        if(Utils.objectIsNotEmpty(shopInfoType)){
            params.put("shopInfoType",shopInfoType);
        }
        List<Map<String ,Object>> shopTransactionSummaryList =shopShopInfoService.queryShopTransactionSummary(params);
        if(Utils.objectIsNotEmpty(shopTransactionSummaryList)){
            for(Map<String,Object> map: shopTransactionSummaryList){
                //结算佣金
                BigDecimal commissionProportion = new BigDecimal(0);
                if(Utils.objectIsNotEmpty(map.get("commission"))){
                    commissionProportion = new BigDecimal(String.valueOf(map.get("commission")));
                }
                BigDecimal transactionAmount= new BigDecimal(0);//交易金额 (己完成交易)
                if(Utils.objectIsNotEmpty(map.get("transactionAmount"))){
                    transactionAmount=new BigDecimal(String.valueOf(map.get("transactionAmount")));
                }
                BigDecimal commissionAmount=new BigDecimal(commissionProportion.multiply(transactionAmount).doubleValue()/100);
                BigDecimal payableAmount = transactionAmount.subtract(commissionAmount);
                map.put("commissionProportion",commissionProportion);
                map.put("commissionAmount",commissionAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
                map.put("payableAmount",payableAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
                if(Utils.objectIsNotEmpty(createTimeStart)){
                    map.put("beginTime",createTimeStart);
                }else {
                    map.put("beginTime","--");
                }
                if(Utils.objectIsNotEmpty(createTimeEnd)){
                    map.put("endTime",createTimeEnd);
                }else {
                    map.put("endTime","--");
                }
            }
        }

        SimpleDateFormat formatter = new SimpleDateFormat(EnumUtils.DataFormat.Y_M_D_H_m_s.getValue());
        List<Map<String,Object>> transactionSummary = new ArrayList<>();
        if(shopTransactionSummaryList!=null&&shopTransactionSummaryList.size()>0){
            for (Map<String,Object> shopTransactionSummary : shopTransactionSummaryList) {
                Map<String,Object> map = new HashMap<>();
                map.put("companyName",shopTransactionSummary.get("companyName"));
                map.put("shopName", shopTransactionSummary.get("shopName"));
                map.put("transactionAmount", shopTransactionSummary.get("transactionAmount"));
                map.put("commissionProportion", shopTransactionSummary.get("commissionProportion"));
                map.put("commissionAmount", shopTransactionSummary.get("commissionAmount"));
                map.put("payableAmount", shopTransactionSummary.get("payableAmount"));
                map.put("beginTime", shopTransactionSummary.get("beginTime"));
                map.put("endTime", shopTransactionSummary.get("endTime"));
                transactionSummary.add(map);
            }
        }

        String fileName ="交易汇总信息（状态）";
        String columnNames[] = {"公司名称","店铺名称","交易金额 (元)","佣金百分比(%)","佣金(元)","平台给店铺结算的应付金额(元)","起始日期","截止日期"};
        String keys[] = {"companyName","shopName","transactionAmount","commissionProportion","commissionAmount","payableAmount","beginTime","endTime"};
        try {
            ExportExcel.download(fileName,transactionSummary,columnNames,keys,request,response);
        } catch (IOException e) {
            logger.error("导出Excel失败！");
        }

    }
}
